package org.example.service;

import org.example.DBConnection;
import org.example.dao.OrderDAO;
import org.example.dao.ProductDAO;
import org.example.entity.Order;
import org.example.entity.OrderItem;
import org.example.entity.Product;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.List;

/**
 * @author xiaomengzi
 * @create 2025-08-04 下午2:53
 */
public class OrderService {
    Connection connection;
    OrderDAO orderDAO;
    ProductDAO productDAO;
    public OrderService() {
        try {
            this.connection = DBConnection.getConnection();
            this.orderDAO = new OrderDAO();
            this.productDAO = new ProductDAO();
        } catch (SQLException e) {
            throw new RuntimeException("数据库连接失败",e);
        }
    }
    public int createOrder(int userId, List<int[]>  items,String shippingAddress) throws SQLException {
        // 计算订单总金额
        connection.setAutoCommit(false);
        Savepoint savepoint = connection.setSavepoint("savepoint");

        try{
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (int[] item : items) {
                int productId = item[0];
                int quantity = item[1];
                Product product = productDAO.getProduct(productId);
                if (product == null) {
                    throw new SQLException("商品不存在，"+"产品ID"+productId+"不存在");
                }
                if(product.getStock() <quantity ){
                    throw new SQLException("商品"+product.getName()+"库存不足，当前库存"+product.getStock()+"，订单数量"+quantity);
                }
                BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(quantity));
                totalAmount = totalAmount.add(itemTotal);
                if (!productDAO.updateStock(productId,product.getStock()-quantity)){
                    throw new SQLException("更新商品"+product.getName()+"库存失败");
                }
            }
            Order order = new Order(userId,totalAmount,shippingAddress);

            for (int[] item : items) {
                int productId = item[0];
                int quantity = item[1];
                Product product = productDAO.getProduct(productId);
                order.getOrderItems().add(new OrderItem(0,order.getId(),productId,quantity,product.getPrice(),product));
            }
            int orderId = orderDAO.createOrder(order);
            connection.commit();
            return orderId;
        }catch (SQLException e){
            connection.rollback(savepoint);
            throw e;
        }finally {
            connection.setAutoCommit(true);
        }
    }
}
